importClass(java.util.HashSet);
importClass(java.util.List);
importClass(java.util.Map);
importPackage(Packages.org.bukkit);
importPackage(Packages.java.io);
importPackage(Packages.java.awt);
importPackage(Packages.javax.imageio);
importPackage(Packages.com.sk89q.worldedit);
importPackage(Packages.com.sk89q.worldedit.schematic);
importPackage(Packages.com.sk89q.worldedit.blocks);
importPackage(Packages.com.sk89q.worldguard.bukkit);
importPackage(Packages.com.sk89q.worldguard.bukkit.commands);


var f = new FileReader("liveplayers.txt");
var sess = context.remember();
var fReader = new BufferedReader(f);
var l;
var liveplayers = new java.util.ArrayList();
while((l = fReader.readLine()) != null){
  liveplayers.add(l);
}
var bigregions = new PrintWriter(new FileWriter("bigregions.txt"));
var pl = Bukkit.getPlayer(player.getName());

var format = SchematicFormat.getFormats().iterator().next();

var worlds = Bukkit.getWorlds().toArray();

for(var wn=0; wn<worlds.length; wn++){
  var w = worlds[wn];
  var rm = WGBukkit.getRegionManager(w);
  player.print(rm);
  var regions = rm.getRegions().keySet().toArray();
  for(var rn=0; rn<regions.length; rn++){
    r = rm.getRegion(regions[rn]);
    owners = r.getOwners().getPlayers();
    tosave = false;
    if(!owners.isEmpty()){
      owners = owners.iterator();
      while(owners.hasNext()){
        owner = owners.next();
        if(liveplayers.contains(owner)) tosave = true;
      }
    }
    if(tosave){
      if(r.volume()>1000000){
        bigregions.println(r.getId());
      }else if(r.volume()<3000){
        rm.removeRegion(r.getId());
      }else{
        var orig = r.getMinimumPoint();
        var size = r.getMaximumPoint().subtract(orig).add(1,1,1);
        var clip = new CuboidClipboard(size,orig);
        var filename = r.getId().replace('/','_')+".schematic";
        Bukkit.getLogger().info("saving "+filename);
        clip.copy(sess);
        format.save(clip,context.getSafeFile("schematics/"+w.getName(), filename));
        player.print(r.getId());
      }
    }else{
      rm.removeRegion(r.getId());
    }
  }
  pl.performCommand("rg save -w "+w.getName());
}
bigregions.close();
